/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.framework.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.legendshop.oa.constants.PageDefinition;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.exception.ErrorCodes;
import com.legendshop.oa.exception.model.UserMessages;

/**
 * Spring MVC controller 基类.
 */
public class BaseController {
	
    public static final String DEFAULT_ERROR_VIEW = "error/error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }


	/**
	 * Save message.
	 * 
	 * @param request
	 *            the request
	 * @param message
	 *            the message
	 */
	public void saveMessage(HttpServletRequest request, String message) {
		if (StringUtils.isNotBlank(message)) {
			List list = getOrCreateRequestAttribute(request, "springMessages", ArrayList.class);
			list.add(message);
		}
	}

	/**
	 * Save error.
	 * 
	 * @param request
	 *            the request
	 * @param errorMsg
	 *            the error msg
	 */
	protected static void saveError(HttpServletRequest request, String errorMsg) {
		if (StringUtils.isNotBlank(errorMsg)) {
			List list = getOrCreateRequestAttribute(request, "springErrors", ArrayList.class);
			list.add(errorMsg);
		}
	}

	/**
	 * Handle exception.
	 * 
	 * @param request
	 *            the request
	 * @param userMessages
	 *            the user messages
	 * @return the string
	 */
	protected String handleException(HttpServletRequest request, UserMessages userMessages) {
		request.setAttribute(UserMessages.MESSAGE_KEY, userMessages);
		return PageDefinition.ERROR_PAGE_PATH;
	}

	/**
	 * Gets the or create request attribute.
	 * 
	 * @param <T>
	 *            the generic type
	 * @param request
	 *            the request
	 * @param key
	 *            the key
	 * @param clazz
	 *            the clazz
	 * @return the or create request attribute
	 */
	public static <T> T getOrCreateRequestAttribute(HttpServletRequest request, String key, Class<T> clazz) {
		HttpSession session = request.getSession();
		Object value = session.getAttribute(key);
		if (value == null) {
			try {
				value = clazz.newInstance();
			} catch (Exception e) {
				ReflectionUtils.handleReflectionException(e);
			}
			session.setAttribute(key, value);
		}
		return (T) value;
	}

	/**
	 * Append param to uri.
	 * 
	 * @param URL
	 *            the uRL
	 * @param paramName
	 *            the param name
	 * @param paramValue
	 *            the param value
	 * @return the string
	 */
	protected static String appendParamToURI(String URL, String paramName, String paramValue) {
		String appendedURI = URL;
		if (null != appendedURI) {
			if (appendedURI.indexOf("?") < 0) {
				appendedURI += "?";
			} else {
				appendedURI += "&";
			}
			appendedURI += (paramName + "=" + paramValue);
		}

		return appendedURI;
	}

	/**
	 * Random numeric.
	 * 
	 * @param random
	 *            the random
	 * @param count
	 *            the count
	 * @return the string
	 */
	private static String randomNumeric(Random random, int count) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < count; i++) {
			int val = random.nextInt(10);
			sb.append(String.valueOf(val));
		}
		return sb.toString();
	}

	/**
	 * Gets the file set.
	 * 
	 * @param request
	 *            the request
	 * @return the file set
	 */
	protected Set<MultipartFile> getFileSet(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Set<MultipartFile> fileset = new LinkedHashSet<MultipartFile>();
		for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {
			String key = it.next();
			MultipartFile file = multipartRequest.getFile(key);
			if (file.getOriginalFilename().length() > 0) {
				fileset.add(file);
			}
		}
		return fileset;
	}


	/**
	 * Check login.
	 * 
	 * @param loginName
	 *            the login name
	 */
	protected String checkLogin(HttpServletRequest request, HttpServletResponse response, String loginName) {
		String result = null;
		if (loginName == null) {
			UserMessages userMessages = new UserMessages(ErrorCodes.UNAUTHORIZED, "It can not edit this object belongs to nologined user ");
			result = handleException(request, userMessages);
		}
		return result;
	}

	/**
	 * Check nullable.
	 * 
	 * @param name
	 *            the name
	 * @param obj
	 *            the obj
	 */
	protected void checkNullable(String name, Object obj) {
		if (obj == null) {
			throw new BusinessException(name + "  is non nullable");
		}
	}

	/**
	 * Gets the session attribute.
	 * 
	 * @param request
	 *            the request
	 * @param name
	 *            the name
	 * @return the session attribute
	 */
	protected Object getSessionAttribute(HttpServletRequest request, String name) {
		Object obj = null;
		HttpSession session = request.getSession(false);
		if (session != null) {
			obj = session.getAttribute(name);
		}
		return obj;
	}

	/**
	 * Sets the session attribute.
	 * 
	 * @param request
	 *            the request
	 * @param name
	 *            the name
	 * @param obj
	 *            the obj
	 */
	protected void setSessionAttribute(HttpServletRequest request, String name, Object obj) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.setAttribute(name, obj);
		}
	}


}
